<template>
  <div class="ads-management">
    <!-- 搜索区域 -->
    <el-card class="!border-none mb-4" shadow="never">
      <el-form class="mb-[-16px]" :model="queryParams" inline>
        <el-form-item label="广告名称">
          <el-input v-model="queryParams.ad_group_name" placeholder="请输入广告名称" clearable />
        </el-form-item>
        <el-form-item label="广告状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100px;">
            <el-option label="投放中" :value="AdStatus.RUNNING" />
            <el-option label="已暂停" :value="AdStatus.PAUSED" />
            <el-option label="已结束" :value="AdStatus.ENDED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPage">搜索</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">新建广告</el-button>
    </div>

    <!-- 列表区域 -->
    <el-card class="!border-none" v-loading="pager.loading" shadow="never">
      <div class="mt-4">
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column label="广告主账户" show-overflow-tooltip width="200">
                        <template #default="scope">
                            <div>{{ scope.row.corporation_name }}</div>
                            <div class="text-gray-400 text-sm mt-1 flex items-center">
                                <span class="inline-block w-[90px]">ID:</span>
                                <span>{{ scope.row.ad_account_id }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;" @click="copyToClipboard(scope.row.ad_account_id)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                            <div class="text-gray-400 text-sm mt-1 flex items-center">
                                <span class="inline-block w-[90px]">授权账户ID:</span>
                                <span>{{ scope.row.account_id }}</span>
                                <el-icon class="ml-2 cursor-pointer" style="color: #4a5dff;" @click="copyToClipboard(scope.row.account_id)">
                                    <CopyDocument />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
          <el-table-column prop="ad_group_name" label="广告名称" min-width="200" show-overflow-tooltip />
          <el-table-column prop="ad_group_id" label="广告组ID" min-width="150" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="bid_amount" label="出价金额(分)" width="120" align="right" />
          <!-- <el-table-column prop="impressions" label="展示次数" width="120" align="right" /> -->
          <!-- <el-table-column prop="clicks" label="点击次数" width="120" align="right" />
          <el-table-column prop="ctr" label="点击率" width="120" align="right" /> -->

          <el-table-column prop="create_time" label="创建时间" width="180" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <!-- <el-button link type="primary" @click="handleEdit(row)">编辑</el-button> -->
              <el-button link type="primary" @click="handleView(row)">查看</el-button>
              <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex mt-4 justify-end">
        <pagination v-model="pager" @change="getLists" />
      </div>
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新建广告' : '编辑广告'"
      width="80%"
    >
      <el-form 
        :model="formData" 
        :rules="rules"
        ref="formRef"
        label-width="120px" 
        class="ad-form"
      >
        <!-- 营销内容 -->
        <div class="form-section">
          <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">营销内容</h3>
          <div class="flex gap-4">
            <el-form-item label="广告名称" prop="ad_group_name" class="flex-1">
              <el-input 
                v-model="formData.ad_group_name" 
                placeholder="请输入广告名称" 
                class="w-full"
              />
            </el-form-item>

            <el-form-item label="广告主账号" prop="account_id" class="flex-1">
              <el-select 
                v-model="formData.account_id" 
                filterable 
                remote 
                reserve-keyword 
                placeholder="请选择广告主账号" 
                :remote-method="remoteSearchAccount" 
                :loading="accountLoading" 
                class="w-full"
                clearable
              >
                <el-option 
                  v-for="item in accountOptions" 
                  :key="item.id" 
                  :label="`${item.account_name}【${item.account_id}】`" 
                  :value="item.account_id"
                >
                  <div class="flex flex-col">
                    <span class="text-gray-400 text-xs">{{ item.account_name }} 【{{item.account_id}}】</span>
                  </div>
                </el-option>
                <template #footer>
                  <div class="flex justify-between items-center p-2 border-t">
                    <span class="text-sm text-gray-500">共 {{ accountTotal }} 项</span>
                    <el-pagination 
                      small 
                      layout="prev, pager, next" 
                      :total="accountTotal" 
                      :page-size="accountPageSize" 
                      :current-page="accountCurrentPage" 
                      @current-change="handleAccountPageChange" 
                    />
                  </div>
                </template>
              </el-select>
            </el-form-item>
          </div>

          <div class="flex gap-4">
            <el-form-item label="营销目的" prop="marketing_goal" class="flex-1">
              <el-select v-model="formData.marketing_goal" class="w-full">
                <el-option label="线索留资" value="MARKETING_GOAL_LEAD_RETENTION" />
                <el-option label="品牌宣传" value="MARKETING_GOAL_BRAND_PROMOTION" />
              </el-select>
            </el-form-item>

            <el-form-item label="教育产品" prop="target_asset_id" class="flex-1">
              <el-select 
                v-model="formData.target_asset_id" 
                placeholder="请选择教育产品" 
                :loading="targetAssetLoading" 
                class="w-full"
                clearable
              >
                <el-option 
                  v-for="item in targetAssetOptions" 
                  :key="item.marketing_asset_id" 
                  :label="item.marketing_asset_name" 
                  :value="item.marketing_asset_id"
                >
                  <div class="flex flex-col">
                    <span>{{ item.marketing_asset_name }}</span>
                    <span class="text-gray-400 text-xs">{{ item.description }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="flex gap-4">
            <el-form-item label="优化目标" prop="optimization_goal" class="flex-1">
              <el-radio-group v-model="formData.optimization_goal" class="w-full">
                <el-radio label="OPTIMIZATIONGOAL_PAGE_RESERVATION">表单预约</el-radio>
                <el-radio label="OPTIMIZATIONGOAL_ONLINE_CONSULTATION">在线咨询</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- <el-form-item label="广告描述" class="w-full">
            <el-input
              v-model="formData.description"
              type="textarea"
              placeholder="请输入广告描述"
              class="w-full"
            />
          </el-form-item> -->
        </div>

        <!-- 广告版位 -->
        <div class="form-section">
          <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">广告版位</h3>
          <el-form-item label="投放位置">
            <el-radio-group v-model="formData.positionType" class="mb-4">
              <el-radio label="auto">自动版位</el-radio>
              <el-radio label="specific">特定版位</el-radio>
            </el-radio-group>

            <el-select
              v-if="formData.positionType === 'specific'"
              v-model="formData.position"
              multiple
              placeholder="请选择特定版位"
              class="w-full"
            >
              <el-option label="微信视频号" value="video" />
              <el-option label="微信朋友圈" value="moments" />
              <el-option label="微信公众号与小程序" value="mp" />
              <el-option label="腾讯平台与内容媒体" value="tencent" />
              <el-option label="优量汇" value="union" />
            </el-select>
          </el-form-item>
        </div>

        <!-- 定向设置 -->
        <div class="form-section">
          <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">定向设置</h3>
          <div class="flex flex-wrap gap-4">
            <el-form-item label="地域" class="w-[calc(50%-8px)]" >
              <el-radio-group v-model="regionType" class="mb-4 w-full">
                <el-radio label="all">不限</el-radio>
                <el-radio label="region">区域</el-radio>
              </el-radio-group>
            
            </el-form-item>
            <el-form-item label="性别" class="w-[calc(50%-8px)]">
                <el-radio-group v-model="formData.gender" class="w-full mb-4">
                  <el-radio label="ALL">不限</el-radio>
                  <el-radio label="MALE">男</el-radio>
                  <el-radio label="FEMALE">女</el-radio>
                </el-radio-group>
              </el-form-item>
          </div>
            <div v-if="regionType === 'region'" class="flex gap-4">
                <el-form-item label="地区选择" class="w-[calc(50%-8px)]">
                
                <!-- <div v-if="regionType === 'region'" class="w-full">
                <el-select v-model="selectedProvince" multiple filterable collapse-tags collapse-tags-tooltip placeholder="请选择省份" :loading="regionLoading" style="width: 32%; margin-right: 2%;">
                  <el-option v-for="item in provinceOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-select v-model="selectedCity" multiple filterable collapse-tags collapse-tags-tooltip placeholder="请选择城市" :loading="regionLoading" :disabled="!selectedProvince.length" style="width: 32%;margin-right: 2%;">
                  <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-select v-model="selectedDistrict" multiple filterable collapse-tags collapse-tags-tooltip placeholder="请选择区县" :loading="regionLoading" :disabled="!selectedCity.length" style="width: 32%;">
                  <el-option v-for="item in districtOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </div> -->
            </el-form-item>
                <el-form-item label="人员类型" class="w-[calc(50%-8px)]">
                    <el-select v-model="formData.person_type" multiple collapse-tags collapse-tags-tooltip placeholder="请选择人员类型" class="w-full">
                        <el-option label="最近去过" value="RECENTLY_IN" />
                        <el-option label="去过" value="VISITED_IN" />
                        <el-option label="居住" value="LIVE_IN" />
                        <el-option label="旅游" value="TRAVEL_IN" />
                        <el-option label="CAA最近去过" value="CAA_RECENTLY_IN" />
                        <el-option label="居住和最近去过" value="LIVE_AND_RECENTLY" />
                        <el-option label="智能定向" value="INTELLIGENCE" />
                    </el-select>
                </el-form-item>
            </div>
        
            <div class="flex gap-4">
               
                <el-form-item label="年龄" class="w-[calc(50%-8px)]">
                <el-radio-group v-model="ageType" class="mb-4">
                  <el-radio label="all">不限</el-radio>
                  <el-radio label="specific">指定年龄</el-radio>
                </el-radio-group>
                <el-select 
                  v-if="ageType === 'specific'"
                  v-model="formData.age" 
                  placeholder="请选择年龄" 
                  multiple 
                  class="w-full"
                >
                  <el-option label="14-18岁" value="14-18" />
                  <el-option label="19-24岁" value="19-24" />
                  <el-option label="25-29岁" value="25-29" />
                  <el-option label="30-39岁" value="30-39" />
                  <el-option label="40-49岁" value="40-49" />
                  <el-option label="50岁及以上" value="50-99" />
                </el-select>
              </el-form-item>
            </div>
        </div>

        <!-- 出价与预算 -->
        <div class="form-section">
            <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">出价与预算</h3>
          <div class="flex flex-wrap gap-4">
            <el-form-item label="出价方式" prop="bid_type" class="w-[calc(50%-8px)]">
              <el-select v-model="formData.bid_type" placeholder="请选择出价方式" class="w-full">
                <el-option label="OCPM" :value="BidType.OCPM" />
                <!-- <el-option label="CPM" :value="BidType.CPM" /> -->
                <!-- <el-option label="CPD" :value="BidType.CPD" /> -->
              </el-select>
            </el-form-item>

            <el-form-item label="出价金额(元)" prop="bid_amount" class="w-[calc(50%-8px)]">
              <el-input-number v-model="formData.bid_amount" :min="0.01" :precision="2" class="w-full" :step="0.01" />
            </el-form-item>

            <!-- <el-form-item label="日预算(分)" class="w-[calc(50%-8px)]">
              <el-input-number v-model="formData.daily_budget" :min="0" :precision="2" class="w-full" :step="0.01" />
            </el-form-item> -->
          </div>
        </div>

        <!-- 广告设置 -->
        <div class="form-section">
          <h3 class="form-section-title" style="font-size: 18px; font-weight: bold;">广告设置</h3>
          <div class="flex flex-wrap gap-4">
            <el-form-item label="投放时间" prop="startTime" class="w-[calc(50%-8px)]">
              <div class="flex items-center gap-2">
                <el-date-picker
                  v-model="formData.startTime"
                  type="date"
                  placeholder="开始时间"
                  class="w-[calc(50%-4px)]"
                  :disabled-date="(time: Date) => {
                    const today = new Date()
                    today.setHours(0, 0, 0, 0)
                    if (formData.endTime) {
                      return time > formData.endTime || time < today
                    }
                    return time < today
                  }"
                  @change="(val: Date | null) => {
                    if (val && formData.endTime && val > formData.endTime) {
                      formData.endTime = val
                    }
                  }"
                />
                <span>至</span>
                <el-date-picker
                  v-model="formData.endTime"
                  type="date"
                  placeholder="结束时间"
                  class="w-[calc(50%-4px)]"
                  :disabled-date="(time: Date) => {
                    const today = new Date()
                    today.setHours(0, 0, 0, 0)
                    if (formData.startTime) {
                      return time < formData.startTime || time < today
                    }
                    return time < today
                  }"
                  @change="(val: Date | null) => {
                    if (val && formData.startTime && val < formData.startTime) {
                      ElMessage.warning('结束时间不能小于开始时间')
                      formData.endTime = formData.startTime
                    }
                  }"
                />
              </div>
            </el-form-item>
<!-- 
            <el-form-item label="投放时段" class="w-[calc(50%-8px)]">
              <el-time-picker
                v-model="formData.timeRange"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                class="w-full"
              />
            </el-form-item> -->
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormItemRule } from 'element-plus'
import type { AdListItem, AdFormData, SearchForm } from '@/types/ads'
import { AdStatus, BidType, AdPosition } from '@/types/ads'
import { usePaging } from '@/hooks/usePaging'
import { getAdsList, createAd, updateAd, deleteAd, getAdDetail,get_targeting_tags, get_target_assets } from '@/api/ads'
import { apiGetAccounts } from '@/api/tencent_ad_creativity'
import { CopyDocument } from '@element-plus/icons-vue'

interface AccountOption {
    ad_account_id: string;
    corporation_name: string;
    account_name: string;
    id: number;
    account_id: string;
}

interface RegionOption {
    id: string;
    name: string;
    children?: RegionOption[];
}

interface TargetAssetOption {
  marketing_asset_id: string;
  marketing_asset_name: string;
  description: string;
}

// 查询条件
const queryParams = reactive({
    ad_group_name: '',
    status: ''
})

// 分页相关
const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: getAdsList,
    params: queryParams
})

// 表格数据
const tableData = computed(() => pager.lists)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const activeTab = ref('content')
const currentAdId = ref('')

// 广告主账号相关
const accountOptions = ref<AccountOption[]>([])
const accountLoading = ref(false)
const accountTotal = ref(0)
const accountCurrentPage = ref(1)
const accountPageSize = ref(10)
const accountKeyword = ref('')

// 区域选择相关
const regionType = ref('all') // 'all' | 'region'
const regionLoading = ref(false)
const provinceOptions = ref<RegionOption[]>([])
const cityOptions = ref<RegionOption[]>([])
const districtOptions = ref<RegionOption[]>([])
const selectedProvince = ref<string[]>([])
const selectedCity = ref<string[]>([])
const selectedDistrict = ref<string[]>([])

// 第三方资产相关
const targetAssetOptions = ref<TargetAssetOption[]>([])
const targetAssetLoading = ref(false)
const targetAssetKeyword = ref('')

// 监听省份变化
watch(selectedProvince, async (newVal) => {
    if (newVal.length > 0) {
        await fetchCityOptions(newVal)
    } else {
        cityOptions.value = []
        districtOptions.value = []
        selectedCity.value = []
        selectedDistrict.value = []
    }
})

// 监听城市变化
watch(selectedCity, async (newVal) => {
    if (newVal.length > 0) {
        await fetchDistrictOptions(newVal)
    } else {
        districtOptions.value = []
        selectedDistrict.value = []
    }
})

// 获取省份列表
const fetchProvinceOptions = async () => {
    regionLoading.value = true
    try {
        const res = await get_targeting_tags({ type: 'province' })
        provinceOptions.value = res || []
    } catch (error) {
        console.error('获取省份列表失败：', error)
        ElMessage.error('获取省份列表失败')
        provinceOptions.value = []
    } finally {
        regionLoading.value = false
    }
}

// 获取城市列表
const fetchCityOptions = async (provinceIds: string[]) => {
    regionLoading.value = true
    try {
        const res = await get_targeting_tags({ 
            type: 'city',
            province_ids: provinceIds
        })
        cityOptions.value = res || []
    } catch (error) {
        console.error('获取城市列表失败：', error)
        ElMessage.error('获取城市列表失败')
        cityOptions.value = []
    } finally {
        regionLoading.value = false
    }
}

// 获取区县列表
const fetchDistrictOptions = async (cityIds: string[]) => {
    regionLoading.value = true
    try {
        const res = await get_targeting_tags({ 
            type: 'district',
            city_ids: cityIds
        })
        districtOptions.value = res || []  
    } catch (error) {
        console.error('获取区县列表失败：', error)
        ElMessage.error('获取区县列表失败')
        districtOptions.value = []
    } finally {
        regionLoading.value = false
    }
}

// 监听区域类型变化
watch(regionType, (newVal) => {
    if (newVal === 'all') {
        selectedProvince.value = []
        selectedCity.value = []
        selectedDistrict.value = []
        formData.region = []
    } else {
        fetchProvinceOptions()
    }
})

// 更新选中的区域
const updateSelectedRegions = () => {
    const regions = []
    if (selectedProvince.value.length > 0) {
        regions.push(...selectedProvince.value)
    }
    if (selectedCity.value.length > 0) {
        regions.push(...selectedCity.value)
    }
    if (selectedDistrict.value.length > 0) {
        regions.push(...selectedDistrict.value)
    }
    formData.region = regions
}

// 监听选中值变化
watch([selectedProvince, selectedCity, selectedDistrict], () => {
    updateSelectedRegions()
})

// 表单数据
const formData = reactive<AdFormData & { 
    account_id: string;
    positionType: 'auto' | 'specific';
    gender: 'ALL' | 'MALE' | 'FEMALE';
    person_type: string[];
    marketing_goal: 'MARKETING_GOAL_LEAD_RETENTION'|'MARKETING_GOAL_BRAND_PROMOTION';
    target_asset_id: string;
    optimization_goal: 'OPTIMIZATIONGOAL_PAGE_RESERVATION'|'OPTIMIZATIONGOAL_ONLINE_CONSULTATION';
}>({
    account_id: '',
    positionType: 'auto',
    gender: 'ALL',
    person_type: [],
    marketing_goal: 'MARKETING_GOAL_LEAD_RETENTION',
    target_asset_id: '',
    optimization_goal: 'OPTIMIZATIONGOAL_PAGE_RESERVATION',
    ad_group_name: '',
    description: '',
    position: [],
    region: [],
    age: [],
    bid_type: BidType.OCPM,
    bid_amount: 0,
    daily_budget: 0,
    startTime: undefined,
    endTime: undefined,
    timeRange: undefined
})

// 获取状态类型
const getStatusType = (status: AdStatus) => {
    const map: Record<AdStatus, 'success' | 'warning' | 'info'> = {
        [AdStatus.RUNNING]: 'success',
        [AdStatus.PAUSED]: 'warning',
        [AdStatus.ENDED]: 'info'
    }
    return map[status]
}

// 获取状态文本
const getStatusText = (status: AdStatus) => {
    const map: Record<AdStatus, string> = {
        [AdStatus.RUNNING]: '投放中',
        [AdStatus.PAUSED]: '已暂停',
        [AdStatus.ENDED]: '已结束'
    }
    return map[status] || '投放中' // 默认返回投放中
}

// 远程搜索广告主账号
const remoteSearchAccount = (query: string) => {
    accountKeyword.value = query
    accountCurrentPage.value = 1
    fetchAccountOptions()
}

// 获取广告主账号选项
const fetchAccountOptions = async () => {
    accountLoading.value = true
    try {
        const params = {"account_role_type":"ACCOUNT_ROLE_TYPE_ADVERTISER",page_no:accountCurrentPage.value,page_size:accountPageSize.value}    
        const { lists,count } = await apiGetAccounts(params)
        if (lists) {
            accountOptions.value = lists || []
            accountTotal.value = count || 0
        } else {
            ElMessage.error('获取广告主账号列表失败')
            accountOptions.value = []
            accountTotal.value = 0
        }
    } catch (error) {
        console.error('获取广告主账号列表失败：', error)
        ElMessage.error('获取广告主账号列表失败')
        accountOptions.value = []
        accountTotal.value = 0
    } finally {
        accountLoading.value = false
    }
}

// 处理广告主账号分页变化
const handleAccountPageChange = (page: number) => {
    accountCurrentPage.value = page
    fetchAccountOptions()
}

// 新建广告
const handleAdd = () => {
    dialogType.value = 'add'
    dialogVisible.value = true
    // 重置表单
    Object.assign(formData, {
        ad_group_name: '',
        description: '',
        position: [],
        region: [],
        age: [],
        bid_type: BidType.OCPM,
        bid_amount: 0,
        daily_budget: 0,
        startTime: undefined,
        endTime: undefined,
        timeRange: undefined
    })
}

// 编辑广告
const handleEdit = async (row: AdListItem) => {
    try {
        dialogType.value = 'edit'
        currentAdId.value = row.id
        const { data } = await getAdDetail(row.id)
        Object.assign(formData, data)
        dialogVisible.value = true
    } catch (error) {
        console.error('获取广告详情失败：', error)
        ElMessage.error('获取广告详情失败')
    }
}

// 查看广告
const handleView = async (row: AdListItem) => {
    try {
        const { data } = await getAdDetail(row.id)
        // TODO: 实现查看逻辑
        console.log('广告详情：', data)
    } catch (error) {
        console.error('获取广告详情失败：', error)
        ElMessage.error('获取广告详情失败')
    }
}

// 删除广告
const handleDelete = async (row: AdListItem) => {
    try {
        await ElMessageBox.confirm('确定要删除该广告吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await deleteAd({
            account_id: row.account_id,
            ad_group_id: row.ad_group_id
        })
        ElMessage.success('删除成功')
        getLists()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除广告失败：', error)
            ElMessage.error('删除广告失败')
        }
    }
}

// 表单引用
const formRef = ref()

// 表单验证规则
const rules: Record<string, FormItemRule[]> = {
  ad_group_name: [
    { required: true, message: '请输入广告名称', trigger: 'blur' }
  ],
  account_id: [
    { required: true, message: '请选择广告主账号', trigger: 'change' }
  ],
  target_asset_id: [
    { required: true, message: '请选择教育产品', trigger: 'change' }
  ],
  bid_amount: [
    { required: true, message: '请输入出价金额', trigger: 'blur' },
    { type: 'number' as const, min: 0.01, message: '出价金额必须大于1分', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 自定义验证函数：检查是否同时选择了三个不限
const validateTargeting = () => {
//   if (regionType.value === 'all' && ageType.value === 'all' && formData.gender === 'ALL') {
//     return false
//   }
  return true
}

// 修改提交函数
const handleSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        
        // 验证定向设置
        if (!validateTargeting()) {
            ElMessage.error('地域、年龄、性别不能同时选择不限')
            return
        }

        const submitData = {
            ...formData,
            optimization_goal: formData.optimization_goal
        }
        
        if (dialogType.value === 'add') {
            await createAd(submitData)
            ElMessage.success('创建成功')
        } else {
            await updateAd(currentAdId.value, submitData)
            ElMessage.success('更新成功')
        }
    } catch (error: any) {
        if (error.response?.data?.message) {
            ElMessage.error({
                message: error.response.data.message,
                duration: 15000
            })
        } else {
            ElMessage.error('表单验证失败，请检查必填项')
        }
        console.error('保存广告失败：', error)
    }
}

// 复制到剪贴板
const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
        ElMessage.success('复制成功')
    }).catch(() => {
        ElMessage.error('复制失败')
    })
}

// 监听广告主账号变化
watch(() => formData.account_id, (newVal) => {
  if (newVal) {
    remoteSearchTargetAsset('')
  } else {
    targetAssetOptions.value = []
    formData.target_asset_id = ''
  }
})

// 远程搜索第三方资产
const remoteSearchTargetAsset = async (query: string) => {
  targetAssetKeyword.value = query
  targetAssetLoading.value = true
  try {
    if (!formData.account_id) {
      ElMessage.warning('请先选择广告主账号')
      return
    }
    const res = await get_target_assets({ 
      account_id: formData.account_id,
      keyword: query 
    })
    console.log('API response:', res)
    if (Array.isArray(res)) {
      targetAssetOptions.value = res
    } else if (res && Array.isArray(res.data)) {
      targetAssetOptions.value = res.data
    } else {
      targetAssetOptions.value = []
      console.warn('Unexpected response format:', res)
    }
  } catch (error) {
    console.error('获取第三方资产列表失败：', error)
    ElMessage.error('获取第三方资产列表失败')
    targetAssetOptions.value = []
  } finally {
    targetAssetLoading.value = false
  }
}

// 初始化
onMounted(() => {
    getLists()
    if (regionType.value === 'region') {
        fetchProvinceOptions()
    }
})

// 在 script setup 部分添加
const ageType = ref('all')

// 监听年龄类型变化
watch(ageType, (newVal) => {
  if (newVal === 'all') {
    formData.age = []
  }
})
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.mx-2 {
  margin: 0 8px;
}

:deep(.el-card) {
  margin-bottom: 16px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-table) {
  margin-top: 16px;
}

:deep(.el-pagination) {
  margin-top: 16px;
  justify-content: flex-end;
}

.region-select {
  display: flex;
  align-items: center;
   margin-bottom: 8px; 
}

.region-select .el-select {
  margin-right: 8px;
}

.region-select .el-select:last-child {
  margin-right: 0;
}
</style>
